<template>
  <div>
    <!-- 进度条 -->
    <el-progress :percentage="percentage" :color="customColorMethod"></el-progress>
    <!-- 内容 -->
    <div>
      <el-form ref="form" :label-position="'top'" :model="check" label-width="80px">
      <el-form-item :label="check.id +'、'+check.title">
        <!-- 单选题 -->
        <el-radio-group v-model="mycheck" v-show="check.checked==0">
          <div style="margin-top: 20px">
            <el-radio label="A" border>A：{{check.A}}</el-radio>
          </div>
          <div style="margin-top: 20px">
            <el-radio label="B" border>B：{{check.B}}</el-radio>
          </div>
          <div style="margin-top: 20px">
            <el-radio label="C" border>C：{{check.C}}</el-radio>
          </div>
          <div style="margin-top: 20px">
            <el-radio label="D" border>D：{{check.D}}</el-radio>
          </div>
        </el-radio-group>
        <!-- 多选题 -->
        <el-checkbox-group v-model="mychecks" v-show="check.checked==1">
          <div style="margin-top: 20px">
            <el-checkbox label="A" border size="medium">A：{{check.A}}</el-checkbox>
          </div>
          <div style="margin-top: 20px">
            <el-checkbox label="B" border size="medium">B：{{check.B}}</el-checkbox>
          </div>
          <div style="margin-top: 20px">
            <el-checkbox label="C" border size="medium">C：{{check.C}}</el-checkbox>
          </div>
          <div style="margin-top: 20px">
            <el-checkbox label="D" border size="medium">D：{{check.D}}</el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    </div>
    <div>
      <el-button-group>
        <el-button @click="decrease" :disabled="up">上一题</el-button>
        <el-button @click="increase" :disabled="down">下一题</el-button>
        <el-button @click="submit" v-show="flag">提交</el-button>
      </el-button-group>
    </div>
    <div>
      展开：<el-switch v-model="value">
      </el-switch>
    </div>
    <div v-show="value">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1]"
        :page-size="1"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 进度条
      percentage: 2.5,
      customColor: '#409eff',
      // 
      value: false,
      currentPage:1,
      // 题库
      checkList:[],
      // 我的选项
      mycheck:'',
      mychecks:[],
      // 每道题目
      check:{},
      // 题目总数
      count:0,
      // 我的答案及题目
      myanswers:[],
      // 上一题下一题按钮
      up:false,
      down:false,
      flag:false,
      scrollvalue:0
    }
  },
  methods:{
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      // 判断题库中是否有本道题目
      this.myanswers.forEach((item,i)=>{
        if(item.id==this.check.id){
          this.myanswers.splice(i,1);
        }
      })
      // 添加
      this.putanswer();

      // console.log(`当前页: ${val}`);
      // 给题目重新赋值
      this.check = this.checkList[val-1]
      // 让进度条增加
      this.percentage = val*this.scrollvalue
      // 给currentPage重新赋值
      this.currentPage = val

      // 下一题点击之后检索题目
      // 判断题库中是否有本道题目
      this.myanswers.forEach((item,i)=>{
        if(item.id==this.check.id){
          this.search();
        }
      })
    },
    init(){
      this.$ajax({
        url:'exam/choice',
        method:'get'
      }).then(resp=>{
        if(resp.data.status==1){

          this.checkList = resp.data.message
          // 乱序数组
          this.checkList.sort(function(){
              return Math.random() - 0.5;
          })
          this.count = resp.data.count
          let userinfo = JSON.parse(localStorage.getItem("user")|| "[]")
          if(userinfo.length==0){
            this.$alert('登录可享有更多特权，例如：查看错题，海量打题', '温馨提示', {
              confirmButtonText: '确定',
              callback: action => {
                
              }
            });
            this.checkList = this.checkList.slice(0,10)
            this.count = 10
          }
          this.scrollvalue = 100 / this.count
          this.percentage = 100 / this.count
          // console.log(this.scrollvalue);
          // console.log(this.count);
          this.check = this.checkList[this.currentPage-1]
        }
      })
    },
    // 进度条
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#909399';
      } else if (percentage < 70) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    increase() {
      // 判断题库中是否有本道题目
      this.myanswers.forEach((item,i)=>{
        if(item.id==this.check.id){
          this.myanswers.splice(i,1);
        }
      })
      // 添加
      this.putanswer();
      
      this.percentage += this.scrollvalue;
      this.currentPage++;
      if (this.percentage > 100) {
        this.percentage = 100;
      }
      if(this.currentPage>=this.count){
        this.currentPage=this.count
      }
      this.check = this.checkList[this.currentPage-1]
      // 判断题库中是否有本道题目
      this.myanswers.forEach((item,i)=>{
        if(item.id==this.check.id){
          this.search();
        }
      })
    },
    decrease() {
      // 判断题库中是否有本道题目
      this.myanswers.forEach((item,i)=>{
        if(item.id==this.check.id){
          this.myanswers.splice(i,1);
        }
      })
      // 添加
      this.putanswer();

      this.percentage -= this.scrollvalue;
      this.currentPage--;
      if (this.percentage <= this.scrollvalue) {
        this.percentage = this.scrollvalue;
      }
      if(this.currentPage<=1){
        this.currentPage=1
      }
      this.check = this.checkList[this.currentPage-1]
      // 回到上一题之后检索题目
      this.search();
    },
    // 储存题目方法
    putanswer(){
      
      // 单选
      if(this.check.checked==0){
        if(this.mycheck!=''){
          this.myanswers.push({id:this.check.id,answer:this.check.answer,checked:this.check.checked,myanswer:this.mycheck});
          this.mycheck=''
        }
        // console.log(this.mycheck);
      }
      // 多选
      else if(this.check.checked==1){
        if(this.mychecks.length>0){
          this.myanswers.push({id:this.check.id,answer:this.check.answer,checked:this.check.checked,myanswer:this.mychecks});
          this.mychecks=[]
        }
        // console.log(this.mychecks);
      }
    },
    // 检索回答过得题目
    search(){
      this.myanswers.forEach(item=>{
        if(item.id==this.check.id){
          // 单选
          if(item.checked==0){
            this.mycheck = item.myanswer
          }
          // 多选
          else if(item.checked==1){
            this.mychecks = item.myanswer
          }
          return true;
        }
      })
    },
    submit(){
      // 添加最后一题
      this.increase();
      // 判断未做的题
      let tkids = []
      this.checkList.forEach(item=>{
        tkids.push(item.id);
      })
      let doids = []
      this.myanswers.forEach(item=>{
        doids.push(item.id)
      })
      let notdis = []
      tkids.forEach(item=>{
        if(!doids.includes(item)){
          notdis.push(item)
        }
      })
      // 未做完不能提交
      if(notdis.length>0){
        alert('还有第'+notdis.toString()+'未做，请返回做完再提交！')
        return;
      }

      // 计算分数
      let grade = 0
      this.myanswers.forEach(item=>{
        if(item.checked==0){
          if(item.answer==item.myanswer){
            grade++
          }
        }else if(item.checked==1){
          if(item.answer==item.myanswer.sort().join("")){
            grade++
          }
        }
      })
      grade = grade * (100 / this.count)

      // 统计错题
      let error = []
      this.myanswers.forEach(item=>{
        if(item.checked==0){
          if(item.answer!==item.myanswer){
            error.push(item)
          }
        }else if(item.checked==1){
          if(item.answer!==item.myanswer.sort().join("")){
            error.push(item)
          }
        }
      })

      // 提交
      this.$confirm('确定提交吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 判断是否登录了
        let userinfo = JSON.parse(localStorage.getItem("user")|| "[]")
        // alert('你获得了'+grade+'分')
        if(userinfo.length==0){
          alert('你获得了'+grade+'分')
        }else{
          //提交  uid 错题集errors  分数grade
          let uid = userinfo[0][0].userinfoId
          let errors = JSON.stringify(error);
          
          // 把错题存储到数据库
          this.$ajax({
            url:'exam/puterrors',
            method:'post',
            data:{uid,errors,grade}
          }).then(resp=>{
            // console.log('你获得了'+grade+'分');
            // console.log('未做的题：');
            // console.log(error);
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.$router.push('/');
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交'
        });          
      });
    }
  },
  created(){
    this.init();
  },
  watch:{
    "currentPage":function(val,oval){
      if(val==1){
        this.up=true;
        this.down=false;
        this.flag=false;
      }else if(val==this.count){
        this.down=true;
        this.up=false;
        this.flag=true;
      }else{
        this.up=false;
        this.down=false;
        this.flag=false;
      }
    }
  }
}
</script>

<style scoped>

</style>